//
//  DownloadDisplayViewController.m
//  Brand
//
//  Created by Lin Eidan on 14-5-16.
//  Copyright (c) 2014年 Faker. All rights reserved.
//

#import "DownloadDisplayViewController.h"
#import "Header.h"
#import "config.h"

#define BigPicImageSrc              @"BigPicImageSrc"

#define NumsOfColumnMovie           3   //多少列
#define NumsOfColumn                4   //多少列

//download
#define ISLoadintImage                  @"Menu"
#define HasPauseImage                   @"downloadM_pause"
#define HasSucceessImage                @"downloadM_play"

#define ISLoadintImageW                  @"down_circle"
#define HasPauseImageW                   @"pause"
#define HasSucceessImageW                @"down_play"

@interface DownloadDisplayViewController ()

@property (weak, nonatomic) IBOutlet UIView *navTopContentView;
@property (strong, nonatomic) IBOutlet UIView *DownloadMovieView;
@property (strong, nonatomic) IBOutlet UIButton *editingButton;
@property (assign, nonatomic) BOOL isInEditing;
@property (strong, nonatomic) IBOutlet UIImageView *weekBgImageView;

//week play
@property (strong, nonatomic) CustomGridView *customGridView;
@property (strong, nonatomic) NSMutableArray *dataArray;

//movie play
@property (strong, nonatomic) CustomGridView *movieGridView;
@property (strong, nonatomic) NSMutableArray *movieDataArray;

@end

@implementation DownloadDisplayViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [Common handleHeightWithIPhone5WithView:self.view];
    
    [self drawNavTopContentView:self.navTopContentView];
    
    [self drawNow];
    // Do any additional setup after loading the view from its nib.
}

-(void)drawNow{
    
    float top = 64;
    if (!isiOS7) {
        top -=20 ;
    }
    
    self.customGridView=[[CustomGridView alloc] initWithFrame:CGRectMake(0, top , self.view.width, self.view.height - top)];
    self.customGridView.customGridViewdataSource=self;
    self.customGridView.customGridViewdelegate=self;
    [self.customGridView setGridViewLeft:12];
    [self.customGridView drawOtherViewBeforeGridView:self.DownloadMovieView andGridViewTop:345];
    [self.view addSubview:self.customGridView];
    
    self.movieGridView=[[CustomGridView alloc] initWithFrame:CGRectMake(0, 36, self.view.width, 110)];
    self.movieGridView.customGridViewdataSource=self;
    self.movieGridView.customGridViewdelegate=self;
    self.movieGridView.scrollEnabled = NO;
    [self.movieGridView setGridViewLeft:5.5];
    [self.DownloadMovieView addSubview:self.movieGridView];
    
    NSString *url = [NSString stringWithFormat:@"%@videoPage",API_BASE];
    
    if ([DownloadVideoManager sharedInstance].downloadQueue.count != 0) {
        [self hasGetNormalDataHandle];
    }
    
    if ([kUser objectForKey:BigPicImageSrc]) {
        [[AFGetData sharedInstance] initSDWebImage:[kUser objectForKey:BigPicImageSrc] andTrueImageView:self.weekBgImageView andPlaceholderImage:nil];
    }
    
    [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        if (isSuccess) {
            NSDictionary *dic = responseObj;
            
            NSString *imageURL = [[dic objectForKey:@"bigPic"] objectForKey:@"pic"];
            [[AFGetData sharedInstance] initSDWebImage:imageURL  andTrueImageView:self.weekBgImageView andPlaceholderImage:nil];
            
            [self handleTheVideoObjWithArray:[dic objectForKey:@"movie"]];
            [self handleTheVideoObjWithArray:[dic objectForKey:@"cartoon"]];
            
            [self hasGetNormalDataHandle];
            
            [[DownloadVideoManager sharedInstance] saveQueueToLocal];
            [kUser setObject:imageURL forKey:BigPicImageSrc];
            [kUser synchronize];
        }else{
            if ([DownloadVideoManager sharedInstance].downloadQueue.count == 0) {
                [PopTips tips:self.view Msg:NotifyDownloadDataInitFailed];
                [self performSelector:@selector(goBack:) withObject:nil afterDelay:0.7];
                return;
            }else{
                [self hasGetNormalDataHandle];
            }
            
        }
    }];
    
    
}

//在本地更新，不再本地新建
-(void)handleTheVideoObjWithArray:(NSArray *)array{
    for (NSDictionary *detailDic in array) {
        BOOL isHas = NO;  //是否已经在 本地。
        for (VideoObj *tempObj in [DownloadVideoManager sharedInstance].downloadQueue) {
            if ([[detailDic objectForKey:@"id"] isEqualToString:tempObj.episodeId]) {
                isHas = YES;
                tempObj.isReadyShow = [[detailDic objectForKey:@"is_ok"] boolValue];
                tempObj.isNeedVIP = [[detailDic objectForKey:@"v_flag"] boolValue];
                break;
            }
        }
        if (!isHas) {
            VideoObj *obj = [self createDownloadVideoObjWithDic:detailDic];
            [[DownloadVideoManager sharedInstance] addTheVideoToDownloadQueueWith:obj];
        }
        
    }    
    
}

-(void)hasGetNormalDataHandle{
    self.movieDataArray=[[NSMutableArray alloc] initWithCapacity:NumsOfColumnMovie];
    self.dataArray=[[NSMutableArray alloc] initWithCapacity:NumsOfColumn];
    for (int i=0; i<NumsOfColumnMovie; i++) {
        NSMutableArray *columnArray=[[NSMutableArray alloc] init];
        [self.movieDataArray addObject:columnArray];
    }
    
    for (int i=0; i<NumsOfColumn; i++) {
        NSMutableArray *columnArray=[[NSMutableArray alloc] init];
        [self.dataArray addObject:columnArray];
    }
    
    //获得数据后，依次放进对应的数组
    for (int i=0; i<NumsOfColumnMovie; i++) {
        [[self.movieDataArray objectAtIndex:i%NumsOfColumnMovie] addObject:[[DownloadVideoManager sharedInstance].downloadQueue objectAtIndex:i]];
    }
    
    for (int i=0; i<[DownloadVideoManager sharedInstance].downloadQueue.count - NumsOfColumnMovie; i++) {
        [[self.dataArray objectAtIndex:i%NumsOfColumn] addObject:[[DownloadVideoManager sharedInstance].downloadQueue objectAtIndex:i+NumsOfColumnMovie]];
    }
    [self reloadData];
    [DownloadVideoManager sharedInstance].delegate = self;
}

-(void)reloadData{
    [self.customGridView reloadData];
    [self.movieGridView reloadData];
}

-(VideoObj *)createDownloadVideoObjWithDic:(NSDictionary *)dic{
    VideoObj *obj = [[VideoObj alloc] init];
    obj.contentId = VideoObjContentId;
    obj.contentName = [dic objectForKey:@"title"];
    obj.imageSrc = [dic objectForKey:@"pic"];
    obj.episodeId = [dic objectForKey:@"id"];
    obj.episodeName = obj.contentName;
    obj.isReadyShow = [[dic objectForKey:@"is_ok"] boolValue];
    obj.isNeedVIP = [[dic objectForKey:@"v_flag"] boolValue];
    return obj;
    
}

#pragma -mark customGridView
//有多少列
-(NSInteger)numberOfColumnsInCustomGridView:(CustomGridView *)customGridView{
    if (customGridView == self.customGridView) {
        return NumsOfColumn;
    }else{
        return NumsOfColumnMovie;
    }
    
}
//每一列有多少个cell
-(NSInteger)customGridView:(CustomGridView *)customGridView numberOfRowsInColumn:(NSInteger)column{
    if (customGridView == self.customGridView) {
        return [[self.dataArray objectAtIndex:column] count];
    }else{
        return [[self.movieDataArray objectAtIndex:column] count];
    }
    
}

//每一列的宽度
-(CGFloat)customGridView:(CustomGridView *)customGridView widthOfColumn:(NSInteger)column{
    float width=74;
    if (customGridView == self.movieGridView) {
        width = 103;
    }
    return width;
}

//每一个cell的高度
-(CGFloat)customGridView:(CustomGridView *)customGridView heightForCellsAtIndexPath:(CustomIndexPath *)indexPath{
    float height=68;
    if (customGridView == self.movieGridView) {
        height = 116;
    }
    return height;
}

-(CGFloat)customGridView:(CustomGridView *)customGridView topSpaceForCellsAtIndexPath:(CustomIndexPath *)indexPath{
    float space =0;
    return space;
}

//每一个cell
-(CustomTableCell *)customGridView:(CustomGridView *)customGridView cellAtIndexPath:(CustomIndexPath *)indexPath{
    
    static NSString *cellIdentifier =@"DownTVCell";  //cellIdentifier同时也是自定义xib的名字。。
    if (customGridView == self.customGridView) {
        cellIdentifier = @"DownTVCell";
    }else{
        cellIdentifier = @"DownMovieCell";
    }
    
    CustomTableCell *cell= [self.customGridView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        cell = [[CustomTableCell alloc] initWithIdentifier:cellIdentifier];
        
    }else{
        
    }
    cell.delegate = self;
    VideoObj *obj;
    UIButton *controlBtn;
    
    if (customGridView == self.movieGridView) {
        obj = [[self.movieDataArray objectAtIndex:indexPath.column] objectAtIndex:indexPath.row];
        UIImageView *trueImageView = (UIImageView *)[cell viewWithTag:302];
        UIImageView *stateView =(UIImageView *)[cell viewWithTag:403];
        controlBtn =  (UIButton *)[cell viewWithTag:201];
        UIView *maskView = [cell viewWithTag:700];
       
        [[DownloadGetData sharedInstance] initSDWebImage:obj.imageSrc andTrueImageView:trueImageView andPlaceholderImage:nil];
        
        if (obj.isLoading) {
            stateView.image=[UIImage imageNamed:ISLoadintImage];
        }else{
            stateView.image=[UIImage imageNamed:HasPauseImage];
        }
        if (obj.isComplete) {
            stateView.image = [UIImage imageNamed:HasSucceessImage];
        }
        
        if (obj.isReadyShow) {
            maskView.hidden = YES;
        }else{
            maskView.hidden = NO;
        }
        
        controlBtn.titleLabel.text=[NSString stringWithFormat:@"%d_%d_movie",indexPath.column,indexPath.row];
        
    }else{
        obj = [[self.dataArray objectAtIndex:indexPath.column] objectAtIndex:indexPath.row];
        UIImageView *stateView =(UIImageView *)[cell viewWithTag:403];
        controlBtn = (UIButton *)[cell viewWithTag:201];
        UILabel *label = (UILabel *)[cell viewWithTag:202];
        
        label.text = obj.episodeName;
        if (!obj.isReadyShow) {
            label.text = @"即将上映";
        }
        
        if (obj.isLoading) {
            stateView.image=[UIImage imageNamed:ISLoadintImageW];
        }else{
            stateView.image=[UIImage imageNamed:HasPauseImageW];
        }
        if (obj.isComplete) {
            stateView.image = [UIImage imageNamed:HasSucceessImageW];
            label.textColor = RGB(18, 35, 72);
        }else{
            label.textColor = [UIColor whiteColor];
        }
        
        controlBtn.titleLabel.text=[NSString stringWithFormat:@"%d_%d_week",indexPath.column,indexPath.row];
    }
    
    [controlBtn addTarget:self action:@selector(cellCliked:) forControlEvents:UIControlEventTouchUpInside];
    
    [self updatePerWithCell:cell andPer:obj.percent];
    
    UIButton *deleteBtn = (UIButton *)[cell viewWithTag:600];
    deleteBtn.titleLabel.text = controlBtn.titleLabel.text;
    [deleteBtn addTarget:self action:@selector(deleteTheFile:) forControlEvents:UIControlEventTouchUpInside];
    if (!self.isInEditing || !obj.isReadyShow) {
        deleteBtn.hidden = YES;
    }else{
        deleteBtn.hidden = NO;
    }
    
    UIImageView *vipImageView = (UIImageView *)[cell viewWithTag:701];
    if (obj.isNeedVIP) {
        vipImageView.hidden = NO;
    }else{
        vipImageView.hidden = YES;
    }
    
    return cell;
    
}

#pragma -mark customGridView clicked
-(void)cellCliked:(id)sender{
    UIButton *btn=(UIButton *)sender;
    VideoObj *videoObj = [self getObjWithClickedBtn:btn];
    
    if (self.isInEditing) {  //编辑点击cell，就回去
        return;
    }
    
    if (!videoObj.isReadyShow) {
        [PopTips tips:self.view Msg:NotifyVideoNotOpen];
        return;
    }
    
    if (videoObj.isNeedVIP) {
        if (![[UserObj sharedInstance] isLegalVip]) {
            [PopTips tips:self.view Msg:NotifyIsNotVip];
            return;
        }
    }
    
    if (videoObj.isComplete) {
        [kHandle sharedInstance].videoPlayerVC = [[VideoPlayerViewController alloc]initWithNibName:@"VideoPlayerViewController" andObj:videoObj andListArray:nil];
        [self presentViewController:[kHandle sharedInstance].videoPlayerVC animated:YES completion:nil];
    }else{
        [[DownloadVideoManager sharedInstance] downloadCellHasClickedWithObj:videoObj];
    }
    
}

-(void)deleteTheFile:(id)sender{
    UIButton *btn=(UIButton *)sender;
    VideoObj *videoObj = [self getObjWithClickedBtn:btn];
    
    if (videoObj.percent == 0.0) {
        [PopTips tips:self.view Msg:NotifyDownloadDataCanNotDel];
        return;
    }
    
    NSArray *removeArray = @[videoObj];
    [[DownloadVideoManager sharedInstance] deleteTheDownloadItemsWithRemoveArray:removeArray andIsDownloading:YES];
    
    [self reloadData];
    NZAlertView *alert = [[NZAlertView alloc] initWithStyle:NZAlertStyleSuccess
                                                     title:NotifyNormal
                                                   message:NotifyDownloadDataDelSuccess
                                                  delegate:nil];
    [alert show];
    
}

-(VideoObj *)getObjWithClickedBtn:(UIButton *)btn{
    NSString *string = btn.titleLabel.text;
    NSArray *tempArray = [string componentsSeparatedByString:@"_"];
    
    NSArray *nowDataArray = [[tempArray objectAtIndex:2] isEqualToString:@"movie"] ? self.movieDataArray : self.dataArray;
    VideoObj *videoObj=[[nowDataArray objectAtIndex:[[tempArray objectAtIndex:0] intValue]] objectAtIndex:[[tempArray objectAtIndex:1] intValue]];
    return videoObj;
}

#pragma -mark DownloadDelegate

-(void)updatePerWithCell:(CustomTableCell *)cell andPer:(float)per{
    //普通方法
    UIView *perBgView=[cell viewWithTag:401];
    UIView *perView=[cell viewWithTag:402];
    perView.height=perBgView.height*per;
    perView.top = perBgView.height - perView.height+1;
}

-(void)handleImageWithTag:(int )tag andImageName:(NSString *)imageName InTableViewCellWithIndex:(int )index{
    UIImageView *imageView=(UIImageView *)[[self getRightCellWithIndex:index] viewWithTag:tag];
    imageView.image=[UIImage imageNamed:imageName];
}

-(CustomTableCell *)getRightCellWithIndex:(int )index{
    CustomTableCell *cell;
    CustomIndexPath *indexPath;
    if(index < NumsOfColumnMovie){
        indexPath = [CustomIndexPath indexPathForRow:0 inColumn:index];
        cell=[self.movieGridView getCellWithIndexPath:indexPath];
    }else{
        index -= NumsOfColumnMovie;
        indexPath = [CustomIndexPath indexPathForRow:index/NumsOfColumn inColumn:index%NumsOfColumn];
        cell = [self.customGridView getCellWithIndexPath:indexPath];
    }
    return cell;
}


-(void)updateHasDownloadPer:(float)per inTheItemWithIndex:(int)index{
    [self updatePerWithCell:[self getRightCellWithIndex:index] andPer:per];
}

-(void)updateFailedUIInTheItemWithIndex:(int)index{
    [self handleImageWithTag:403 andImageName:(index < NumsOfColumnMovie ? HasPauseImage : HasPauseImageW) InTableViewCellWithIndex:index];
}

-(void)updateStartDownLoadUIInTheItemWithIndex:(int)index{
    [self handleImageWithTag:403 andImageName:(index < NumsOfColumnMovie ? ISLoadintImage : ISLoadintImageW) InTableViewCellWithIndex:index];
}

-(void)updateSuccessUIInTheItemWithIndex:(int)index{
    [self handleImageWithTag:403 andImageName:(index < NumsOfColumnMovie ? HasSucceessImage : HasSucceessImageW) InTableViewCellWithIndex:index];
    
    if (index >= NumsOfColumnMovie) {
        UILabel *label = (UILabel *)[[self getRightCellWithIndex:index] viewWithTag:202];
        label.textColor = RGB(18, 35, 72);
    }
    [Common getWYByPostWithType:@"8" andItemId:@"0"];
}


#pragma -mark xib clicked
- (IBAction)enterOrExitEidingMode:(id)sender {
    if (!self.isInEditing) {  //点击进入编辑模式
        self.isInEditing = YES;
        self.editingButton.selected = YES;
    }else{
        self.isInEditing = NO;
        self.editingButton.selected = NO;
    }
    
    [self reloadData];
}

- (IBAction)goBack:(id)sender {
    [DownloadVideoManager sharedInstance].delegate = nil;
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
